package com.party.web.web.controller.member;

import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.commune.CIntegralItem;
import com.party.core.model.commune.CIntegralMedal;
import com.party.core.model.commune.CIntegralType;
import com.party.core.model.commune.IntegralType;
import com.party.core.model.member.MemberGroup;
import com.party.core.service.commune.ICIntegralBizService;
import com.party.core.service.commune.ICIntegralItemService;
import com.party.core.service.commune.ICIntegralMedalService;
import com.party.core.service.commune.ICIntegralTypeService;
import com.party.core.service.member.IMemberGroupService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import com.party.web.web.security.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * @program: party
 * @description: 积分类型控制器
 * @author: Hua Qunhao
 * @create: 2019-08-12 18:56
 **/
@Controller
@RequestMapping("member/integral/integralType")
public class IntegralTypeController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ICIntegralTypeService integralTypeService;

    @Autowired
    private ICIntegralItemService integralItemService;

    @Autowired
    private ICIntegralMedalService integralMedalService;

    @Autowired
    private IMemberGroupService memberGroupService;

    @Autowired
    private ICIntegralBizService integralBizService;

    /**
     * @Description:积分类型列表
     * @Param:CIntegralType
     * @return:ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/8/13
     */
    @RequestMapping("/list")
    public ModelAndView list(CIntegralType cIntegralType, CommonInput input, Page page) {
        page.setLimit(20);
        ModelAndView mv = new ModelAndView("member/integralTypeList");
        Map<String, Object> params = CommonInput.appendParams(input);
        if (StringUtils.isNotEmpty(cIntegralType.getName())) {
            params.put("name", cIntegralType.getName());
        }
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
//        List<String> orgIds = memberGroupService.getChildWithMy(currentUser.getId());
//        params.put("orgIds", orgIds);
        //params.put("createBy", currentUser.getId());
        boolean isChild = currentUser.isChild();
        if (!isChild) {
            params.put("createBy", currentUser.getId());
        } else {
            params.put("createBy", currentUser.getPartnerId());
        }
        List<CIntegralType> cIntegralTypes = integralTypeService.webPageList(params, page);
        for (CIntegralType ctObj : cIntegralTypes) {

            CIntegralItem cIntegralItem = new CIntegralItem();
            cIntegralItem.setTypeId(ctObj.getId());
            cIntegralItem.setCreateBy(ctObj.getCreateBy());
            Integer itemNum = integralItemService.getItemNum(cIntegralItem);
            ctObj.setItemNum(itemNum);
        }

        if (null != params.get("startDate")) {
            input.setCreateStart(params.get("startDate").toString().substring(0, "2018-05-04".length()));
        }
        if (null != params.get("endDate")) {
            input.setCreateEnd(params.get("endDate").toString().substring(0, "2018-05-04".length()));
        }

        mv.addObject("cIntegralTypes", cIntegralTypes);
        mv.addObject("cIntegralType", cIntegralType);
        mv.addObject("input", input);
        mv.addObject("page", page);
        mv.addObject("isChild", isChild);
        return mv;
    }

    /**
     * @Description:积分类型详情
     * @Param:CIntegralType
     * @return:ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/8/13
     */
    @RequestMapping("/form")
    public ModelAndView form(String id) {
        ModelAndView mv = new ModelAndView("member/integralTypeForm");
        MemberGroup currentUser = RealmUtils.getCurrentUser();

        CIntegralType cIntegralType = integralTypeService.get(id);
        mv.addObject("cIntegralType", cIntegralType);


        //是否存在推荐类型
        CIntegralType reuOrg = integralBizService.getCIntegralType(currentUser.getId(), IntegralType.CINTEGRALTYPE_CATEGORY_RECOMMEND.getCode());
        //是否存在赠送类型
        CIntegralType giftOrg = integralBizService.getCIntegralType(currentUser.getId(), IntegralType.CINTEGRALTYPE_CATEGORY_GIFT.getCode());
        Map<Integer, String> categorys = IntegralType.convertMap();
        if (reuOrg != null && (StringUtils.isEmpty(id) || (StringUtils.isNotEmpty(id) && !reuOrg.getId().equals(id)))) {
            categorys.remove(IntegralType.CINTEGRALTYPE_CATEGORY_RECOMMEND.getCode());
        }
        if (giftOrg != null && (StringUtils.isEmpty(id) || (StringUtils.isNotEmpty(id) && !giftOrg.getId().equals(id)))) {
            categorys.remove(IntegralType.CINTEGRALTYPE_CATEGORY_GIFT.getCode());
        }
        mv.addObject("categorys", categorys);
        return mv;
    }


    /**
     * @Description:编辑积分类型
     * @Param:CIntegralType
     * @return:AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/13
     */
    @ResponseBody
    @RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult saveOrUpdate(CIntegralType ciType) {
        try {
            if (StringUtils.isEmpty(ciType.getName())) {
                return AjaxResult.error("参数为空");
            }
            if (!(IntegralType.CINTEGRALTYPE_CATEGORY_GIFT.getCode() == ciType.getCategory())) {
                if (StringUtils.isEmpty(ciType.getMedalUrl())) {
                    return AjaxResult.error("奖牌不能为空");
                }
            }

            MemberGroup currentUser = RealmUtils.getCurrentUser();

            //判断该机构下是否存在推荐类型
            CIntegralType reuRgo = integralBizService.getCIntegralType(currentUser.getId(), IntegralType.CINTEGRALTYPE_CATEGORY_RECOMMEND.getCode());
            if (reuRgo != null && (!reuRgo.getId().equals(ciType.getId())) && IntegralType.CINTEGRALTYPE_CATEGORY_RECOMMEND.getCode() == ciType.getCategory()) {
                return AjaxResult.error("已存在推荐积分类型，不能重复添加");
            }

            //积分类型保存
            CIntegralType queryObj = new CIntegralType();
            queryObj.setName(ciType.getName());
            queryObj.setCreateBy(currentUser.getId());
            List<CIntegralType> list = integralTypeService.list(queryObj);
            if (list.size() > 0) {
                CIntegralType cIntegralType = list.get(0);
                if (cIntegralType.getId().equals(ciType.getId())) {
                    integralTypeService.update(ciType);
                } else {
                    return AjaxResult.error("积分类型已存在");
                }
            } else {
                if (StringUtils.isEmpty(ciType.getId())) {
                    ciType.setCreateBy(currentUser.getId());
                    integralTypeService.insert(ciType);
                } else {
                    integralTypeService.update(ciType);
                }
            }

/*            if (!(IntegralType.CINTEGRALTYPE_CATEGORY_GIFT.getCode() == ciType.getCategory())) {
                //奖牌保存
                CIntegralMedal cIntegralMedal = new CIntegralMedal();
                cIntegralMedal.setTypeId(ciType.getId());
                List<CIntegralMedal> list1 = integralMedalService.list(cIntegralMedal);
                for (CIntegralMedal cmObj : list1) {
                    integralMedalService.delete(cmObj.getId());
                }
                int soft = 0;
                for (CIntegralMedal cm : ciType.getResources()) {
                    cm.setSoft(soft);
                    cm.setTypeId(ciType.getId());
                    integralMedalService.insert(cm);
                    soft++;
                }
            }*/
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("编辑积分类型异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("编辑积分类型异常");
        }
    }

    /**
     * @Description:删除积分类型
     * @Param:id
     * @return:AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/13
     */
    @ResponseBody
    @RequestMapping("/delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delete(String id) {
        try {
            if (StringUtils.isEmpty(id)) {
                return AjaxResult.error("参数为空");
            }
            CIntegralType cIntegralType = integralTypeService.get(id);
            if (cIntegralType == null) {
                logger.error("积分类型不存在");
                return AjaxResult.error("积分类型不存在");
            }
            List<CIntegralItem> list = integralItemService.list(new CIntegralItem("", id));
            if (list.size() > 0) {
                logger.error("该积分类型下存在积分项，不能直接删除");
                return AjaxResult.error("该积分类型下存在积分项，不能直接删除");
            }
            if (IntegralType.CINTEGRALTYPE_CATEGORY_RECOMMEND.getCode() == cIntegralType.getCategory()) {
                logger.error("不能删除推荐积分类型");
                return AjaxResult.error("不能删除推荐积分类型");
            }
            cIntegralType.setDelFlag(BaseModel.DEL_FLAG_DELETE);
            integralTypeService.update(cIntegralType);

/*            CIntegralMedal cIntegralMedal = new CIntegralMedal();
            cIntegralMedal.setTypeId(id);
            List<CIntegralMedal> list1 = integralMedalService.list(cIntegralMedal);
            for (CIntegralMedal cmObj : list1) {
                integralMedalService.delete(cmObj.getId());
            }*/
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("删除积分类型异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("删除积分类型异常");
        }
    }

    /**
     * @Description:获取全部积分类型
     * @Param:
     * @return:AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/13
     */
    @ResponseBody
    @RequestMapping("/listAll")
    public List<CIntegralType> listAll(Integer category) {
        try {
            CurrentUser currentUser = RealmUtils.getNewCurrentUser();
            CIntegralType cIntegralType = new CIntegralType();
            cIntegralType.setCreateBy(currentUser.getId());
            if (currentUser.isChild()) {
                cIntegralType.setCreateBy(currentUser.getPartnerId());
            }
            if (category != null) {
                cIntegralType.setCategory(category);
            }
            List<CIntegralType> list = integralTypeService.list(cIntegralType);
            return list;
        } catch (Exception e) {
            logger.error("获取全部积分类型异常", e);
            return null;
        }
    }
}
